package cn.jy.boot.controller;

import com.google.code.kaptcha.Producer;
import com.sun.deploy.net.HttpResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.awt.image.BufferedImage;
import java.io.IOException;

@RestController
public class VerifycodeController {

    private final Producer producer;

    @Autowired
    public VerifycodeController(Producer producer) {
        this.producer = producer;
    }

    @RequestMapping("/vc.jpg")
    public void getVerifyCode(HttpServletResponse response, HttpSession session) throws IOException {

        response.setContentType("image/png");//设置相应类型为图片
        String code = producer.createText();//生成验证码
        session.setAttribute("kaptcha", code);//将验证码存入session中             可以更换成 redis 实现
        BufferedImage bi = producer.createImage(code);//将验证码创建为图片
        ServletOutputStream os = response.getOutputStream();//
        ImageIO.write(bi, "jpg", os);//响应图片
    }
}
